'use strict';

// 通过 require 引入 vk 实例
const vk = require('vk-unicloud');
// 通过 vk.init 初始化 vk实例（只有初始化后才能使用）
vk.init({
	baseDir: __dirname,
	requireFn: require
});


/**
 * 此处建议只改下订单状态，保证能及时返回给第三方支付服务器成功状态
 * 且where条件可以增加判断服务器推送过来的金额和订单表中订单需支付金额是否一致
 * 将消息发送、返佣、业绩结算等业务逻辑异步处理(写入异步任务队列表)
 * 如开启定时器每隔5秒触发一次，处理订单
 */
module.exports = async (obj, originalParam) => {
	let user_order_success = true;
	let {
		data = {}, verifyResult
	} = obj;
	let {
		db,
		_
	} = originalParam;
	let {
		openid,
		out_trade_no,
		total_fee,
		user_id,
		bean_number,
		transaction_id,
		recharge_balance
	} = data;
	// 此处写你自己的支付成功逻辑开始-----------------------------------------------------------

	//先判断是否存在out_trade_no和total_fee，不存在则直接返回失败
	if (!out_trade_no || !total_fee) {
		user_order_success = false;
		return user_order_success;
	}
	console.log("微信支付返回的data", data);

	let orderinfo = await db.collection('a_recharge').where({
		out_trade_no: out_trade_no
	}).get()
	console.log("看看订单数据", orderinfo);
	//判断订单金额和实付金额是否一致
	if (orderinfo.data[0].recharge_amount != total_fee) {
		//添加金豆收支明细
		const add_error = await db.collection('vk-test').add({
			user_id: user_id,
			orderinfo: orderinfo.data[0],
			remark: "实付金额和订单金额不一致，疑似抓包",
			_add_time: data._add_time,
			_add_time_str: data._add_time_str
		})
		console.log("订单金额和实付金额不一致");
		return res;
	}

	let recharge_all = await vk.baseDao.count({
		dbName: "a_recharge", // 表名
		whereJson: { // 条件
			pay_status: 1,
			user_id: user_id,
		}
	});

	//修改充值记录订单，状态为已支付，并记录实付金额，微信支付订单号等
	const update_order = await db.collection('a_recharge').where({
		out_trade_no: out_trade_no
	}).update({
		openid: openid,
		shifu_amount: total_fee,
		transaction_id: transaction_id,
		pay_status: 1,
		recharge_all: recharge_all + 1,
		_add_time: data._add_time,
		_add_time_str: data._add_time_str
	})

	if (data.subject == "充值金豆") {
		console.log("充值成功！", openid);
		//如果修改成功，给用户增加金豆数量
		//此方法腾讯云和阿里云都支持
		let newInfo = await vk.baseDao.updateAndReturn({
			dbName: "uni-id-users",
			whereJson: {
				_id: user_id
			},
			dataJson: {
				is_paid: true,
				had_youhui: true, //had_youhui可以判断用户是否付费过，便于付费用户数量统计
				balance: _.inc(bean_number)
			}
		});

		//更新用户充值后的金豆数
		// const update_changed_num = await db.collection('a_recharge').where({
		// 	out_trade_no: out_trade_no
		// }).update({
		// 	changed_num: newInfo.balance, //支付后金豆余额
		// })

		//添加金豆收支明细
		const add_jindou = await db.collection('a_jindou_detail').add({
			user_id: user_id,
			nickname: newInfo.nickname || "未绑定",
			change_num: bean_number, //增加的金豆数量
			changed_num: newInfo.balance, //支付后金豆余额
			change_reason: "支付" + total_fee + "分钱充值" + bean_number + "金豆",
			type: "income", //类型：expend:支出,income:收入。
			appid: newInfo.appid || "",
			appname: newInfo.appname || "",
			_add_time: data._add_time,
			_add_time_str: data._add_time_str
		})
	}
	if (data.subject == "自定义会员") {
		let addtime = 0;
		const onedaytime = 86400000 //1天
		const onehourtime = 3600000 //1小时

		if (orderinfo.data[0].days) {
			addtime = onedaytime * orderinfo.data[0].days
		}
		if (orderinfo.data[0].hour) {
			addtime = onehourtime * orderinfo.data[0].hour
		}

		//先查询用户信息，是否已是会员
		let getres = await db.collection('uni-id-users').doc(user_id).field({
			plus_expire_time: true
		}).get()


		var nowtime = new Date().getTime()
		const plus_expire = getres.data[0].plus_expire_time
		if (plus_expire * 1 < nowtime * 1) {
			let new_expire_time = nowtime * 1 + addtime;
			//如果会员已到期，会员时间就是当前时间+addtime
			let updateVip = await db.collection('uni-id-users').doc(user_id).update({
				is_paid: true, //记录用户已支付
				plus_type: 1,
				plus_expire_time: new_expire_time
			})
		} else {
			console.log("修改用户会员到期时间");
			let new_expire_time2 = plus_expire * 1 + addtime
			//如果会员没有到期，会员时间就是到期时间+addtime
			let updateVip2 = await db.collection('uni-id-users').doc(user_id).update({
				is_paid: true, //记录用户已支付
				plus_expire_time: new_expire_time2
			})
		}
	}
	if (data.subject == "单剧会员") {
		let newInfo = await vk.baseDao.updateAndReturn({
			dbName: "uni-id-users",
			whereJson: {
				_id: user_id
			},
			dataJson: {
				is_paid: true,
				had_youhui: true, //had_youhui可以判断用户是否付费过，便于付费用户数量统计
			}
		});
		//添加金豆收支明细
		let add_djhy = await db.collection('a_djhy').add({
			user_id: user_id,
			nickname: orderinfo.data[0].nickname || "未绑定",
			tv_name: orderinfo.data[0].tv_name,
			tv_id: orderinfo.data[0].tv_id,
			appid: orderinfo.data[0].appid || "",
			appname: orderinfo.data[0].appname || "",
			_add_time: data._add_time,
			_add_time_str: data._add_time_str
		})
	}
	if (data.subject == "开通会员" || data.subject == "年度会员" || data.subject == "季度会员" || data.subject == "月度会员") {
		let addtime = 0;
		//【开通会员】这个类型是为了兼容老版本的年费会员
		if (data.subject == "开通会员") {
			addtime = 31536000000 //365天
		}
		if (data.subject == "年度会员") {
			addtime = 31536000000 //365天
		}
		if (data.subject == "季度会员") {
			addtime = 7776000000 //90天
		}
		if (data.subject == "月度会员") {
			addtime = 2592000000 //30天
		}
		//先查询用户信息，是否已是会员
		let getres = await db.collection('uni-id-users').doc(user_id).field({
			plus_expire_time: true
		}).get()

		var nowtime = new Date().getTime()
		const plus_expire = getres.data[0].plus_expire_time
		if (plus_expire * 1 < nowtime * 1) {
			let new_expire_time = nowtime * 1 + addtime;
			//如果会员已到期，会员时间就是当前时间+addtime
			let updateVip = await db.collection('uni-id-users').doc(user_id).update({
				is_paid: true, //记录用户已支付
				plus_type: 1,
				plus_expire_time: new_expire_time
			})
		} else {
			console.log("修改用户会员到期时间");
			let new_expire_time2 = plus_expire * 1 + addtime
			//如果会员没有到期，会员时间就是到期时间+addtime
			let updateVip2 = await db.collection('uni-id-users').doc(user_id).update({
				is_paid: true, //记录用户已支付
				plus_expire_time: new_expire_time2
			})
		}
	}



	//判断概率回传和比例回传部分
	let num_recharge_one = await vk.baseDao.count({
		dbName: "a_recharge", // 表名
		whereJson: { // 条件
			user_id: user_id,
			pay_status: 1
		}
	});
	if (num_recharge_one == 1) {
		// 返回被修改的记录条数
		let num = await vk.baseDao.update({
			dbName: "a_recharge", // 表名
			whereJson: { // 条件
				out_trade_no: out_trade_no
			},
			dataJson: { // 需要修改的数据
				is_first: true
			}
		});
	}

	//======获取回传比例开始======
	let percent = null
	let tfurlpercent = await db.collection('a_config').where({
		name: "RebackPercent",
		tfid: orderinfo.data[0].tfid //添加这条数据的代理商ID
	}).get()


	if (tfurlpercent.data.length != 0) {
		percent = tfurlpercent
	} else {
		percent = await db.collection('a_config').where({
			name: "RebackPercent",
			user_id: orderinfo.data[0].invite_code || 0 //添加这条数据的代理商ID
		}).get()
	}

	let Radios = 0;
	if (percent.data[0]) {
		console.log("存在代理商比例数据", percent);
		if (orderinfo.data[0].tg_pt == "douyin") {
			Radios = percent.data[0].douyinRadio * 1 || 0;
		}
		if (orderinfo.data[0].tg_pt == "baidu") {
			Radios = percent.data[0].baiduRadio * 1 || 0;
		}
		if (orderinfo.data[0].tg_pt == "kuaishou") {
			Radios = percent.data[0].kuaishouRadio * 1 || 0;
		}
		if (orderinfo.data[0].tg_pt == "tengxun") {
			Radios = percent.data[0].tengxunRadio * 1 || 0;
		}

	} else {
		console.log("不存在代理商比例数据");
	}
	console.log("Radios", Radios);
	//判断是否循环回传
	//循环回传模式
	if (Radios === 1) {
		await vk.callFunction({
			name: "hedian",
			url: 'client/user/pub/proportional_callabck',
			title: '请求中...',
			data: {
				out_trade_no: out_trade_no, //充值订单号
				total_fee: total_fee, //支付金额
				_add_time: data._add_time,
				_add_time_str: data._add_time_str,
				percent: percent
			},
		});
		console.log("进行了比例回传函数");
		await addvktest("进行了比例回传");
	} else {
		//百分比回传模式
		// 云函数内调用其他云函数或云对象内的函数,进行付费数据回传。
		let callRes = await vk.callFunction({
			name: "hedian",
			url: 'client/user/pub/callback',
			data: {
				out_trade_no: out_trade_no, //充值订单号
				total_fee: total_fee, //支付金额
				_add_time: data._add_time,
				_add_time_str: data._add_time_str
			},
		});
		console.log("进行了概率回传")
		await addvktest("进行了概率回传");
		return user_order_success;
	}


	//快手回传

	//腾讯回传



	//百度回传

	return user_order_success;
	async function addvktest(tips) {
		let addvktest = await db.collection('callback_log').add({
			tips: tips,
			out_trade_no: out_trade_no,
			total_fee: total_fee,
			_add_time: _add_time,
			_add_time_str: _add_time_str
		})
	}
};